package cc.lucien.web.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class FileUploadUtil {

    @SuppressWarnings("description")
    public static String upload(Integer id, MultipartFile picture, HttpServletRequest request) {
        try {
            InputStream inputStream = picture.getInputStream();
            // 获取项目在运行期间某个路劲对应磁盘的真实路径
            String realPath = request.getServletContext().getRealPath("/files/");
            File file = new File(realPath, picture.getOriginalFilename());

            File file1 = new File("E:/code/java/java-qruan/ssm/src/main/webapp/files/", picture.getOriginalFilename());

            FileOutputStream outputStream = new FileOutputStream(file);

            FileOutputStream outputStream1 = new FileOutputStream(file1);

            byte[] bytes = new byte[1024 * 1024 * 10];
            int len = 0;
            while ((len = inputStream.read(bytes, 0, bytes.length)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            len = 0;
            inputStream = picture.getInputStream();
            while ((len = inputStream.read(bytes, 0, bytes.length)) != -1) {
                outputStream1.write(bytes, 0, len);
            }

            // 关闭资源
            outputStream1.close();
            outputStream.close();
            inputStream.close();
            return "/files/" + picture.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
